import asyncdispatch, asyncnet
import net
var 
  clients = newSeq[AsyncSocket]()
  server: AsyncSocket  # 提升为全局变量以便异常恢复

proc processClient(client: AsyncSocket) {.async.} =
  try:
    while true:
      let data = await client.recv(1024)
      if data.len == 0: break
      echo "[DEBUG] 收到数据: ", data
      await client.send("Echo: " & data)
  except:
    echo "[WARN] 客户端异常断开"
    clients.del(clients.find(client))
    client.close()

proc startServer(port = 8888) {.async.} =
  try:
    server = newAsyncSocket()
    server.setSockOpt(OptReuseAddr, true)
    server.bindAddr(Port(port))
    server.listen()
    
    echo "[INFO] 服务器启动成功，监听端口 ", port
    echo "serviceIP:", getPrimaryIPAddr()
    while true:
      let client = await server.accept()
      echo "[CONN] 新客户端来自: ", client.getPeerAddr()
      clients.add(client)
      asyncCheck processClient(client)
      
  except OSError as e:
    echo "[FATAL] 网络错误: ", e.msg
    quit(1)
  except Exception as e:
    echo "[ERROR] 意外错误: ", e.msg
    quit(1)

when isMainModule:
  # 主事件循环
    waitFor startServer()
    runForever()  # 新增：保持事件循环持续运行      